import { useState } from "react";
import { useModel } from "umi";
import { Form, Input, Select, Button, message, Space } from "antd";
import { useReactive } from "ahooks";

import useUpdatePosition from "../../hooks/position/useUpdatePosition";
import userCheckPositionNameNoSelf from "../../hooks/position/userCheckPositionNameNoSelf";

const EditPositionModle = ({ item, reloadData }) => {
    const { onCloseGlobalModal } = useModel("global.modal");

    const { updatePosition } = useUpdatePosition();
    const { checkPositionNameNoSelf } = userCheckPositionNameNoSelf();

    const [form] = Form.useForm();

    const state = useReactive({
        loading: false,
    });

    let onFinish = async (values) => {
        state.loading = true;
        let variables = {
            opUuid: item.opUuid,
            opName: values.opName.trim(),
            opDesc: values.opDesc ? values.opDesc.trim() : "",
        };
        let res = await updatePosition(variables);
        if (res) {
            message.success("成功更新职位信息");
            reloadData();
            form.resetFields();
            onCloseGlobalModal();
        }
        state.loading = false;
    };

    const opNameValidator = async (rule, value) => {
        if (value && validates.titleAndName(value) && value.length < 31) {
            let res = await checkPositionNameNoSelf({ opName: value, notEqualTo: item.opUuid });
            console.log(res);
            if (res === null) return Promise.reject("检查职位名称出错");
            return res > 0 ? Promise.reject("职位名称重复！") : Promise.resolve();
        } else {
            return Promise.reject("职位名称只能输入中文、英文、数字，最多30个汉字");
        }
    };

    return (
        <Form form={form} layout="vertical" onFinish={onFinish} style={{ padding: 20 }} initialValues={item}>
            <Form.Item label="职位名称" name="opName" validateTrigger="onBlur" rules={[{ required: true, validator: opNameValidator }]}>
                <Input placeholder="请输入" />
            </Form.Item>

            <Form.Item label="职位说明" name="opDesc">
                <Input.TextArea placeholder="请输入" />
            </Form.Item>

            <div style={{ marginTop: 20, textAlign: "center" }}>
                <Space>
                    <Button loading={state.loading} type="primary" htmlType="submit" style={{ width: "100%" }}>
                        提交
                    </Button>
                    <Button loading={state.loading} onClick={() => form.resetFields()}>
                        重置
                    </Button>
                </Space>
            </div>
        </Form>
    );
};

export default EditPositionModle;
